package _11_整理题目._3_字符串_递归_dfs_bfs_双指针._矩阵搜索;

import org.junit.Test;

public class _10_岛屿数量 {

    private int m;
    private int n;
    private int count;
    private boolean[][] visited;

    public int solve (char[][] grid) {
        m = grid.length;
        n = grid[0].length;
        visited = new boolean[m][n];
        for(int i=0; i<m; i++) {
            for(int j=0; j<n; j++) {
                if(!visited[i][j] && grid[i][j]=='1') {
                    dfs(grid, i, j);
                    count++;
                }
            }
        }
        return count;
    }

    public void dfs(char[][] grid, int i, int j) {
        if(i < 0 || i >= m || j < 0 || j >= n) return;
        if(grid[i][j] == '0' || visited[i][j]) return;

        visited[i][j] = true;
        dfs(grid, i+1, j);
        dfs(grid, i-1, j);
        dfs(grid, i, j+1);
        dfs(grid, i, j-1);
    }

    @Test
    public void main() {
        char[][] grid = {
                {'1','1','0','0','0'},
                {'0','1','0','1','1'},
                {'0','0','0','1','1'},
                {'0','0','0','0','0'},
                {'0','0','1','1','1'},
        };
        System.out.println(solve(grid));
    }
}
